<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.productId ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'"
    >
      <el-form-item label="产品名称" prop="productName">
        <el-input
          class="wd_50"
          v-model="dataForm.productName"
          placeholder="产品名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="产品标题" prop="title">
        <el-input
          class="wd_50"
          v-model="dataForm.title"
          placeholder="产品标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否免费" prop="freeInd">
        <el-radio v-model="dataForm.freeInd" :label="1">免费</el-radio>
        <el-radio v-model="dataForm.freeInd" :label="2">付费</el-radio>
      </el-form-item>
      <el-form-item label="是否置顶" prop="isTop">
        <el-radio v-model="dataForm.isTop" :label="1">置顶</el-radio>
        <el-radio v-model="dataForm.isTop" :label="2">不置顶</el-radio>
      </el-form-item>
      <el-form-item label="产品图片" prop="mainPic">
        <el-upload
          class="avatar-uploader"
          :action="updateApiurl"
          :show-file-list="false"
          :on-success="successHandle"
          :before-upload="beforeUploadHandle">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="金额" prop="total">
        <el-input class="wd_50" v-model="dataForm.total" placeholder="金额"></el-input>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-input
          class="wd_50"
          v-model="dataForm.priority"
          placeholder="优先级"
        ></el-input>
      </el-form-item>
      <el-form-item label="级别" prop="gradeId">
        <el-select  v-model="dataForm.gradeId" placeholder="请选择对应的用户等级">
          <el-option v-for="item in gradeList"
            :key="item.gradeId"
            :label="item.gradeName"
            :value="item.gradeId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="剩余数量" prop="quantityNumber">
        <el-input
          class="wd_50"
          v-model="dataForm.quantityNumber"
          placeholder="剩余数量"
        ></el-input>
      </el-form-item>
      <el-form-item label="浏览数量" prop="browsesNumber">
        <el-input
          class="wd_50"
          v-model="dataForm.browsesNumber"
          placeholder="浏览数量"
        ></el-input>
      </el-form-item>
      <el-form-item label="库存总数" prop="totalNumber">
        <el-input
          class="wd_50"
          v-model="dataForm.totalNumber"
          placeholder="库存总数"
        ></el-input>
      </el-form-item>
      <el-form-item label="产品内容" prop="content">
        <!-- <el-input v-model="dataForm.content" placeholder="产品内容"></el-input> -->
        <!-- <mavon-editor /> -->
        <quill-editor v-model="dataForm.content" ref="myQuillEditor" ></quill-editor>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<style>
.wd_50 {
  width: 75%;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }

</style>

<script>
import debounce from "lodash/debounce";
import Upload from "../oss/oss-upload";
import Cookies from 'js-cookie'
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        productId: "",
        productName: "",
        title: "",
        mainPic: "",
        content: "",
        freeInd: "1",
        total: "",
        isTop: "2",
        priority: "",
        gradeId: "",
        quantityNumber: "",
        browsesNumber: "",
        totalNumber: "",
        createDate: "",
        updateDate: "",
      },
      gradeList:[],
      uploadVisible: false,
      imageUrl:'',
      updateApiurl :`${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${Cookies.get('token')}`
    };
  },
  computed: {
    dataRule() {
      return {
        productName: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        title: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        mainPic: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        content: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        freeInd: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        total: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        isTop: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        priority: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        gradeId: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        quantityNumber: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        browsesNumber: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        totalNumber: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        updateDate: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
      };
    },
  },
  components: {
    Upload,
  },
  created() {
    this.getGradeList();
  },
  methods: {
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        console.log(this.dataForm)
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get(`/product/product/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          this.imageUrl=this.dataForm.mainPic
        })
        .catch(() => {});
    },
    getGradeList () {
      this.$http.get('/member/grade/list').then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.gradeList = {
          ...this.gradeList,
          ...res.data
        }
      }).catch(() => {})
    },
     // 上传之前
     beforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
        return false
      }
    },
        // 上传成功
    successHandle (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.imageUrl = res.data.src
      this.dataForm.mainPic=this.imageUrl
      console.log(res)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          console.log(this.dataForm)
          this.$http[!this.dataForm.productId ? "post" : "put"](
            "/product/product/",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
